@echo off
setlocal enabledelayedexpansion

echo MySQL Schema Sync Tool - Build Script
echo =====================================

:: Set variables
set BINARY_NAME=mysql-sync
set VERSION=
set BUILD_TIME=
set LDFLAGS=

:: Get version from git if available
for /f "tokens=*" %%i in ('git describe --tags --always --dirty 2^>nul') do set VERSION=%%i
if "%VERSION%"=="" set VERSION=dev

:: Get build time
for /f "tokens=*" %%i in ('powershell -Command "Get-Date -Format 'yyyyMMddHHmmss'"') do set BUILD_TIME=%%i

:: Set linker flags
set LDFLAGS=-ldflags "-X main.version=%VERSION% -X main.buildTime=%BUILD_TIME% -w -s"

:: Create build directory
if not exist build mkdir build

if "%1" == "linux" (
    echo Building for Linux...
    docker run --rm -v "%cd%":/app -w /app golang:1.21 ^
        sh -c "CGO_ENABLED=0 GOOS=linux go build -tags netgo %LDFLAGS% -extldflags '-static' -o build/%BINARY_NAME%-linux ./main.go"
    if !errorlevel! equ 0 (
        echo Linux build completed successfully
    ) else (
        echo Linux build failed
        exit /b 1
    )
) else if "%1" == "static" (
    echo Building static binary...
    set CGO_ENABLED=0
    set GOOS=linux
    go build -tags netgo %LDFLAGS% -extldflags "-static" -o build/%BINARY_NAME%-static ./main.go
    if !errorlevel! equ 0 (
        echo Static build completed successfully
    ) else (
        echo Static build failed
        exit /b 1
    )
) else (
    echo Building for Windows...
    go build %LDFLAGS% -o build/%BINARY_NAME%.exe ./main.go
    if !errorlevel! equ 0 (
        echo Windows build completed successfully
        echo.
        echo Binary created: build/%BINARY_NAME%.exe
        echo Version: %VERSION%
        echo Build time: %BUILD_TIME%
    ) else (
        echo Windows build failed
        exit /b 1
    )
)

echo.
echo Build completed successfully!
echo.
echo Usage examples:
echo   build\%BINARY_NAME%.exe -version
echo   build\%BINARY_NAME%.exe -conf conf.json
echo   build\%BINARY_NAME%.exe -conf conf.json -sync

endlocal